package com.echatim.controller.fileserver;

import com.broker.base.protocol.response.Resp;
import com.commom.AppRespError;
import com.commom.Config;
import com.commom.NumberGenerator;
import com.echatim.ApplicationWrapper;
import com.echatim.service.app.SdkAppService;
import com.exception.ServiceException;
import com.utils.Beans;
import com.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 本地文件服务器 API
 *
 * @author Daizhiqiang
 * @date 2019/11/22 18:07
 */
@Slf4j
@ConditionalOnProperty(name="echatim.sdk.auth-type", havingValue="community")
@Component
public class FileApi {
	@Autowired
	private SdkAppService sdkAppService;

	/**
	 * 创建WEB直传的签名和上传ObjectName
	 */
	public Resp<FileUploadRequestDTO> createWebUploadSign(FileUploadRequestForm form, Long signatureExpireMs){
		// check sdkKey is valid?
		Resp<Void> sdkResp = sdkAppService.verifySDKKey(form.getSdkKey());
		if(!sdkResp.ok()){
			throw new ServiceException(AppRespError.SDK_KEY_INVALID);
		}

		String host = Beans.strNotEmpty(Config.get(ApplicationWrapper.getContext(), "echatim.file.host")) ? Config.get(ApplicationWrapper.getContext(), "echatim.file.host") : "http://localhost";
		FileUploadRequestDTO dto = new FileUploadRequestDTO();
		dto.setSignature("signature-" + UUIDUtils.gen());
		dto.setDir(getFileUploadDir(form));
		dto.setHost(host);
		long expireEndTime = new Date().getTime() + signatureExpireMs; // 60s后就失效
		dto.setExpire(expireEndTime / 1000);  // signature expire time

		return Resp.ok(dto);
	}


	/**
	 *   文件服务器 的路径名定义:
	 *   echatim + 文件类型(file,image,other) + 日期(yyyy/MM/dd) + 时间戳(yyyyMMddhhmmss) + _ + 原始文件名
	 *   如:
	 *   echatim/file/yyyy/MM/dd/timestamp_filename.jpg
	 * */
	private String getFileUploadDir(FileUploadRequestForm form) {
		String applicationName = Config.get(ApplicationWrapper.getContext(), "spring.application.name");
		return (Beans.strNotEmpty(applicationName) ? applicationName : "") + "/" +
				(Beans.strNotEmpty(form.getSdkKey()) ? form.getSdkKey() : "") + "/" +
				(Beans.strNotEmpty(form.getFileType()) ? form.getFileType().toLowerCase() : "file") + "/" +
				(new SimpleDateFormat("yyyy"+"/"+"MM"+"/"+"dd").format(new Date())) + "/" +
				(NumberGenerator.fileNameGenerate()) + "_" + form.getFileName()
				;
	}

}
